package com.order.itemcategoryproject.controller;

import com.order.itemcategoryproject.pojo.dArcCertificate;
import com.order.itemcategoryproject.pojo.dArcStaff;
import com.order.itemcategoryproject.service.dArcCertificateService;
import com.order.itemcategoryproject.service.dArcStaffService;
import com.order.itemcategoryproject.utils.AjaxResult;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

import static com.order.itemcategoryproject.utils.ParseUrl.getUrl;

@RestController
@RequestMapping("/api")
public class dArcCertificateController {


    @Autowired
    private dArcCertificateService dArcCertificateService;
    @Autowired
    private dArcStaffService dArcStaffService;


    /**
     * 根据商品编号以及客户代码获取当前客户下可用证书
     * @param itemId
     * @param request
     * @return
     */
    @RequestMapping("/getCertificateById/{itemId}")
    public AjaxResult getAllCertificateByCodeAndItemId(@PathVariable String itemId, HttpServletRequest request) {
        String queryString = request.getQueryString();
        String code = getUrl(queryString, "StaffID");

        // 判断当前客户下商品可用证书
        if (StringUtils.isBlank(itemId) || StringUtils.isBlank(code)){
            return AjaxResult.error("当前参数未被定义!!!!!!");
        }

        // 获取当前客户
        dArcStaff staffInfo = dArcStaffService.getStaffInfoByStaId(code);

        // 如果获取到这些参数，那么就直接对此进行判断
        List<dArcCertificate> dArcCertificates = null;
        if (ObjectUtils.isNotEmpty(staffInfo) && StringUtils.isNotBlank(staffInfo.getCus_segmentation())) {
            dArcCertificates = dArcCertificateService.selectAllUsefulCertificate(code, itemId, staffInfo.getCus_segmentation());
        } else {
            return AjaxResult.error("为获取到当前客户信息.");
        }

        // 首先判断当前获取到的证书对象是否不为空
        if (ObjectUtils.isEmpty(dArcCertificates)) {
            return AjaxResult.error("当前客户下没有可用证书!!!!!!");
        }

        // 如果存在， 那么直接返回到后端
        return AjaxResult.success(dArcCertificates);
    }


    @GetMapping("/downloadPDF")
    public ResponseEntity<Resource> downloadPDFFile(@RequestParam String fileUrl) throws MalformedURLException {
        // 创建 UrlResource
        String encodedFileUrl = null;
        try {
           encodedFileUrl =  URLEncoder.encode(fileUrl, String.valueOf(StandardCharsets.UTF_8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String fullFilePath = "https://newerp.mumuso.com/uploadfile/" + encodedFileUrl;
        Resource resource = new UrlResource(fullFilePath);

        if (!resource.exists()) {
            throw new RuntimeException("File not found: " + fileUrl);
        }

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename());
        headers.setContentType(MediaType.APPLICATION_PDF);

        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }
}
